#!/usr/bin/python
# -*- coding:utf8-*-

"""
导入火币网kline数据
每个小时运行一次
"""
import json

import utils

TABLE_HUOBI_TRADE_KILINE = 'huobi_trade_data_kline'


class Exchange_data_import:
    def __init__(self, lis_url, table):
        self.u = utils.CoinTools()
        self.conn = self.u.mysqlconnect()
        self.cur = self.conn.cursor()
        self.lis_url = lis_url
        self.table = table

    def run(self):
        lis = []
        for item in self.lis_url:
            data = self.u.doGet(item)
            dic = json.loads(data, encoding='utf8')
            if dic and dic['status'] == 'ok':
                for i in dic['data']:
                    symbol = str(item).split('=')[-1]
                    ts = self.u.secondts_2_mints(long(i['id']))
                    open = i['open']
                    close = i['close']
                    low = i['low']
                    high = i['high']
                    amount = i['amount']
                    vol = i['vol']
                    count = i['count']
                    lis.append((symbol, ts, open, close, low, high, amount, vol, count))
        if lis:
            self.insert(lis)

    def insert(self, lis):
        print lis[0]
        if self.table == TABLE_HUOBI_TRADE_KILINE:
            sql = """insert into """ + TABLE_HUOBI_TRADE_KILINE + """ (symbol, ts, open, close, low, high, amount, vol, count) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
            print sql
            self.cur.executemany(sql, lis)
            self.conn.commit()

    def __del__(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()


def main():
    tool = utils.CoinTools()
    # 火币网
    lis = ['btc', 'eth', 'bch', 'ltc', 'neo']
    lis_huobi_symbol = ['etcbtc', 'bchbtc', 'ltcbtc', 'neobtc']
    url_huobi_rest_api = tool.readini('exchanges_teade_data', 'URL_HUOBI_REST_API')
    url_huobi_kline = tool.readini('exchanges_teade_data', 'URL_HUOBI_KLINE')
    lis_huobi = []
    for item in lis_huobi_symbol:
        url = url_huobi_rest_api + url_huobi_kline + item
        lis_huobi.append(url)
    if lis_huobi:
        huobi = Exchange_data_import(lis_huobi, TABLE_HUOBI_TRADE_KILINE)
        huobi.run()


if __name__ == '__main__':
    main()
